﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QxFramework.Core;

public class PositionSuspendFunc : ItemFunc
{

    private float Strength;
    private float Angle;
    private float MyX;
    private float MyY;
    private float LayX;
    private float LayY;
    private float Distance;
    [Header("弹簧的弹性系数")]
    public float k;
    private float a;
    private bool Lay;
    private float eps = 1e-5f;
    CombinableItem item;
    private Vector3 FlashStart;
    private Vector3 FlashEnd;
    private GameObject Flash;
    private GameObject Anchor;
    protected GameObject Start;
    private void OnEnable()
    {

        item = GetComponent<CombinableItem>();
        Lay = false;
        Start = this.transform.Find("Start").gameObject;
    }
    public override void KeyDownPreference()
    {
        base.KeyDownPreference();
        if (Lay == true)
        {
            FlashStart = new Vector3(LayX, LayY, 0);
            Flash = ResourceManager.Instance.Instantiate("Prefabs/Effects/Flash");
            Anchor = ResourceManager.Instance.Instantiate("Prefabs/Effects/Anchor");
            Anchor.transform.position = FlashStart;
            Refresh();
        }
        else
        {
            if (Flash != null)
            {
                ObjectPool.Recycle(Flash);
                ObjectPool.Recycle(Anchor);

            }
            Flash = null;
        }
    }
    public override void KeyDownInvoke()
    {
        base.KeyDownInvoke();
        if (Lay == false)
        {
            LayX = this.transform.position.x;
            LayY = this.transform.position.y;
       //     FlashStart = new Vector3(LayX, LayY, 0);
            Lay = true;
      //      Flash = ResourceManager.Instance.Instantiate("Prefabs/Effects/Flash");
        //    Refresh();
        }
        else
        {
            Lay = false;
        }
    }
    public override void OnDestory()
    {
        base.OnDestory();
        ObjectPool.Recycle(Flash);
        ObjectPool.Recycle(Anchor);

    }
    void Refresh()
    {

        MyX = Start.transform.position.x;
        MyY = Start.transform.position.y;
    //    item.AddForceAtLocalPosition(Vector3.zero, -new Vector3(MyX - LayX, MyY - LayY, 0) * k);
        FlashEnd = new Vector3(MyX, MyY, 0);
        var list = Flash.GetComponentsInChildren<Flash>();
        foreach (var x in list)
        {
            x.endPos = FlashEnd;
            x.startPos = FlashStart;
            x.Refresh();
        }

    }
    void FixedUpdate()
    {
        if (Lay == true)
        {
            MyX = this.transform.position.x;
            MyY = this.transform.position.y;
            item.AddForceAtLocalPosition(Vector3.zero,-new Vector3(MyX-LayX,MyY-LayY,0)*k);
            Refresh();
        }
    }
}
